package net.esj.basic.core.engine.config;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.LinkedHashSet;
import java.util.Properties;
import java.util.Set;

import net.esj.basic.exception.MelonException;
import net.esj.basic.utils.GetClassLoader;
import net.esj.basic.utils.StringUtils;

import org.apache.log4j.Logger;

public abstract class MelonConfig {
	
	protected static final Logger logger = Logger.getLogger(MelonConfig.class);
	
	public static final String DEFAULT_MELON_CONFIG_NAME = "melon.properties";

	private static Properties properties ;
	
	private static Set<Configuration> configurations = new LinkedHashSet<Configuration>();
	
	private static void loadProp(){
		if(properties==null){
			URL propertiesUrl = GetClassLoader.fromContext().getResource(DEFAULT_MELON_CONFIG_NAME);
			if (propertiesUrl == null) {
				logger.debug(DEFAULT_MELON_CONFIG_NAME+" missing");
				return;
			}
			properties = new Properties();
			InputStream in = null;
			try {
				in = propertiesUrl.openStream();
				properties.load(in);
			} catch (IOException e) {
				throw new MelonException("Could not load " + propertiesUrl.getPath() + ".properties:"
						+ e, e);
			} finally {
				if (in != null) {
					try {
						in.close();
					} catch (IOException io) {
						logger.warn("Unable to close input stream", io);
					}
				}
			}
		}
	}
	
	public static String getProperty(String key){
		if(properties==null){
			loadProp();
		}
		String ret = null;
		if(properties!=null){
			Object o = properties.get(key);
			if(o!=null){
				ret = o.toString();
			}
		}
		if(!StringUtils.hasText(ret)){
			for(Configuration config:configurations){
				ret = config.getProperty(key);
				if(StringUtils.hasText(ret)){
					break;
				}
			}
		}
		return ret;
	}

	public static String getProperty(String key, String defaults) {
		if(properties==null){
			loadProp();
		}
		String ret = null;
		if(properties!=null){
			ret = getProperty(key);
		}
		if(!StringUtils.hasText(ret)){
			for(Configuration config:configurations){
				ret = config.getProperty(key, defaults);
				if(StringUtils.hasText(ret)){
					break;
				}
			}
		}
		if(!StringUtils.hasText(ret)){
			ret = defaults;
		}
		return ret;
	}
	
	public static final void registryConfiguration(Configuration configuration){
		MelonConfig.configurations.add(configuration);
	}
}
